<?php
/**
 * Created by b17
 * 2/27/12 7:27 PM
 */

namespace Managers;

class SubCategory extends BaseManager
{
    const TABLE = '\Catalog\SubCategory';

    protected $__table = self::TABLE;

    protected function createQueryBuilder()
    {
        $qb = parent::createQueryBuilder()
            ->select('sc, c')
            ->from($this->__table, 'sc')
            ->join('sc.category', 'c')
            ->andWhere('sc.isDel = 0')
            ->andWhere('c.isDel = 0');
        return $qb;
    }

    public function getByCategories($categories)
    {
        $categoriesIds = Utils::rebuildArray($categories);
        $qb = $this->createQueryBuilder();
        $qb->andWhere($qb->expr()->in('c.id', $categoriesIds));
        $res = $qb->getQuery()->getArrayResult();

        return $res;
    }

    public function getById($id)
    {
        $qb = $this->createQueryBuilder()
            ->andWhere('sc.id = :id')->setParameter('id', $id);
        $res = $qb->getQuery()->getArrayResult();

        return count($res) ? $res[0] : false;
    }

    /**
     * @param $subcategories
     * @return SelectElement[]
     */
    public function getSelectList($subcategories)
    {
        $items = array();
        foreach ($subcategories as $subcat) {
            $items[] = new SelectElement($subcat['id'], $subcat['name']);
        }
        return $items;
    }


    public function getByCategory($categoryId)
    {
        $qb = $this->createQueryBuilder()
            ->andWhere('c.id = :category')->setParameter('category', $categoryId);
        $res = $qb->getQuery()->getArrayResult();

        return $res;
    }
}
